import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import urllib
from google.appengine.api import urlfetch

import sys
import httplib
import re
import string

import datastore
import library
from datetime import date

class League(db.Model):

 def scrap(self,id):
    r = self.getPlayers( id )
    
    playerlist=[]
    for p in r:  
       g = datastore.Player( key_name= p[0] )
       g.id = p[0]
       g.usta = p[1]
       g.lname = p[2]
       g.fname = p[3]
       g.name =  g.fname + " " + g.lname
       g.city =  p[4]
       g.gender =  p[5]
       g.rating =  p[6] 
       print p
       playerlist.append(g)
 
    db.put( playerlist )


 def getPlayers(self,id):
    def Add(data):
      return ',"' + data + '"'

    url  = "http://www.ustanorcal.com/teaminfo.asp?id="+str(id) 
    result = urlfetch.fetch(url)
    scraped = result.content

    year  = league = level = ""

# <a href=playermatches.asp?id=15067>Lynch, Carl H 
#   Get id , lname,fname,city, place holder, rating
#                                             id        lname               fname                                city
    rexp = r"<a href=playermatches\.asp\?id=([\d]*)>([ \-\w\d\'\.]*)[, ]*([ \-\w\d\'\.]*)[ <>\w=#\d\/]*?nowrap>([ \w]*)"
#                                           gender                  rating
    rexp += r"([ <>\/=#\d\w]* align=center)>(M|F)<([ \/td<>=#\d\w]*)>(\d\.\d\w)*<"


#   Get the player name
    r = re.compile(rexp,re.IGNORECASE )
    player = r.findall( scraped )

# (0)id (1)lname (2)fname (3)city) (4)junk (5)gender (4)junk (7)rating
    roster = []
    for id,name in enumerate(player):
       usta = library.getUSTANumber(name[0])
       roster.append(  (name[0],usta,name[1],name[2],name[3] ,name[5] ,name[7])  )

    return roster

# ------------------------

class MainPage(webapp.RequestHandler):

  def Write(self,t):
    self.response.out.write(t)

  def get(self):
    id =  self.request.get('id') 
    cup = League()
    cup.scrap(id)  

application = webapp.WSGIApplication(
                                     [('/player', MainPage)],
                                     debug=True)



def main():
    run_wsgi_app(application)

if __name__ == "__main__":

#   print __file__
#   print __name__

    main()
